<?php
/**
 * 医疗器械专用发货单
 * AUTHOR  : zlf
 * DateTime: 2022/07/27
 */
namespace App\V3\V3_1\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use App\V3\V3_1\Services\MedicalDeliverOrderService;
use Illuminate\Support\Facades\DB;
use App\V3\V3_1\Models\MedicalDeliverProductsModel;
use App\V3\V3_1\Models\MedicalDeliverOrderModel;
use App\V3\V3_1\Models\AdminAddendumModel;
use OSS\OssClient;

class MedicalDeliverOrderController extends BaseController
{
    protected $ossClient;
    public function __construct(Request $request){
        parent::__construct($request);
        $this->ossClient=new OssClient(
            config('app.aliyun_oss_key'),
            config('app.aliyun_oss_secret'),
            config('app.aliyun_oss_endpoint')
            );
    }
    /**
     * 添加医疗器械专用发货单
     */
    public function add(Request $request){

        $admininfo   = AdminAddendumModel::select('is_vip','empty_bill_amount')->where(['main_id'=>$this->getMainUserId()])->first()->toArray();

        if(!empty($admininfo) && in_array($admininfo['is_vip'],[1,2])){

          /*   $total_amount = DispatchListService::countReceiptsTotal(['main_id'=>$this->getMainUserId()]);

            if($admininfo['empty_bill_amount'] != -1 && $total_amount >= $admininfo['empty_bill_amount']){

                return $this->fail('','您创建的医疗器械专用发货单，已达到设置数量！');
            } */

        }else{

            return $this->fail('','您还不是VIP会员，还不能创建空白单据！');
        }

        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'total_cost'            =>'numeric|min:0',//总费用
        ],[
            'total_cost.numeric'   => '总金额只能为数字',
            'total_cost.min'       => '总金额最小只能为0',
          ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => ''
            ]);
        }
        if(!empty($data['total_cost'])){
            if(getDecimalPointLeng($data['total_cost']) >7){
                return response()->json(['code' => 1,'msg' => '总金额小数点后，不能超过6位数字！','data' => '']);
            }
        }
        if(!empty($unit_stamp_files = $request->file('unit_stamp'))){

            if($unit_stamp_files->isValid()){

                $img_path = $unit_stamp_files->store('yz/imgs/'.date('Y').'-'.date('m').'-'.date('d'));

                $imgRes  = self::addOssUploadImg($this->getMainUserId(),$this->ossClient, $unit_stamp_files, $img_path);
                if($imgRes['code'] === 0){
                    $data['unit_stamp'] = $imgRes['data'];
                }else{
                    return response()->json($imgRes);
                }
            }else{
                return response()->json(['code' => 1,'msg' => '单位印章，有错误！','data' => '']);
            }
        }
        //开启事务
        DB::beginTransaction();
        try{
            //医疗器械专用发货单
            $dData = $data;
            $dData['user_id']      = $this->getUserId();
            $dData['main_id']      = $this->getMainUserId();
            $dData['created_at']   = time();
            unset($dData['goods_info']);
            $medical_deliver_id   = MedicalDeliverOrderService::add($dData);
            /* $data['goods_info']='[
            {"name":"葡萄","type_name":"紫","product_unit":"红富士","price":"5.6","num":"10","serial_number":11,"manufacturer":"掌上网络1","batch_number":"ZS45647547567","date_in_produced":"2022-07-30 21:30:30","effective_date":"2023-07-30 21:30:30","storage_condition":"温度在15度以下","registration_number":"zc3252543253656546"},
            {"name":"水梨","type_name":"黄","product_unit":"砀山梨","price":"3.6","num":"8","serial_number":22,"manufacturer":"掌上网络1","batch_number":"ZS45647547567","date_in_produced":"2022-07-30 21:30:30","effective_date":"2023-07-30 21:30:30","storage_condition":"温度在15度以下","registration_number":"zc3252543253656546"}
            ]'; */
            //商品详细添加
            if(isset($data['goods_info']) && !empty($data['goods_info'])){

                $goodsInfo = json_decode($data['goods_info'],true);
                if(is_array($goodsInfo)){
                    foreach ($goodsInfo as &$value){

                        $value['created_at']          = time();
                        $value['medical_deliver_id'] = $medical_deliver_id;
                        $value['user_id']             = $this->getUserId();
                        $value['main_id']             = $this->getMainUserId();
                    }

                    MedicalDeliverProductsModel::insert($goodsInfo);
                }
            }

            DB::commit();//提交事务
            $this->log("添加医疗器械专用发货单", $dData);
            return $this->success();
        }catch (\Exception $e){
            DB::rollBack();//事务回滚
            //异常响应
            return $this->fail($e->getMessage(),'添加医疗器械专用发货单');
        }

    }

    /**
     * 删除医疗器械专用发货单信息
     * @param ids (删除多个逗号分隔)
     */
    public function delete(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'ids'       =>'required',//医疗器械专用发货单id
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg'  => $info,
                'data' => '',
            ]);
        }

        $id_data = [];
        $id_arr  = explode(',',$data['ids']);

        $condition['user_id'] = $this->getUserId();
        $condition['main_id'] = $this->getMainUserId();

        $list = MedicalDeliverOrderModel::select('id','unit_stamp')->where($condition)->whereIn('id',$id_arr)->get()->toArray();

        if(!empty($list)){

            foreach ($list as $k=>$v){

                $id_data[]=$v['id'];
            }
            DB::beginTransaction();
            try {
            $bool = MedicalDeliverOrderModel::where($condition)->whereIn('id',$id_data)->delete();
            if($bool){
                MedicalDeliverProductsModel::where($condition)->whereIn('medical_deliver_id',$id_data)->delete();

                    foreach ($list as $lk=>$lv){

                        if(!empty($lv['unit_stamp'])){
                            $delOssRes = self::delOssFilePath($lv['unit_stamp'], $this->ossClient, $this->getMainUserId());
                            if(!empty($delOssRes)) return $this->fail('',$delOssRes);
                        }
                    }

                DB::commit();
                $this->log("删除医疗器械专用发货单", $id_data);
                return $this->success();
            }else{
                return $this->fail('','删除失败');
            }
            } catch (\Exception $e) {
                DB::rollBack();
                return $this->fail('',$e->getMessage());
            }
        }

          return $this->fail('','医疗器械专用发货单，不存在！');
    }

    /**
     * 删除商品
     * @param Request $request
     */
    public function delGoods(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'goods_ids'         => 'required',//商品id
            'medical_deliver_id'      => 'required',//医疗器械专用发货单id
        ],[
            'medical_deliver_id.required' => '医疗器械专用发货单主键id`缺失`',
            'goods_ids.required' => '商品主键id`缺失`'

        ]);

        $id_arr  = explode(',',$data['goods_ids']);

        $condition['user_id'] = $this->getUserId();
        $condition['main_id'] = $this->getMainUserId();
        $condition['medical_deliver_id'] = $data['medical_deliver_id'];
        MedicalDeliverProductsModel::where($condition)->whereIn('id',$id_arr)->delete();
        $this->log("删除医疗器械专用发货单商品", $id_arr);
        return $this->success();
    }

    /**
     * 修改医疗器械专用发货单
     *
     */
    public function update(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'medical_deliver_id'   =>'required|integer',//医疗器械专用发货单id
            'total_cost'            =>'numeric|min:0',//总费用
        ],[
            'medical_deliver_id.required'   => '医疗器械专用发货单主键id缺失',
            'medical_deliver_id.integer'   => '医疗器械专用发货单主键id为正整数',
            'total_cost.numeric'   => '总金额只能为数字',
            'total_cost.min'       => '总金额最小只能为0',
          ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        if(!empty($data['total_cost'])){
            if(getDecimalPointLeng($data['total_cost']) >7){
                return response()->json(['code' => 1,'msg' => '总金额小数点后，不能超过6位数字！','data' => '']);
            }
        }
        $info = MedicalDeliverOrderService::getMedicalDeliverOrderInfo(['id'=> $data['medical_deliver_id']]);

        if(empty($info)){

            return $this->fail('','医疗器械专用发货单号,不存在！');
        }
        if(!empty($unit_stamp_files = $request->file('unit_stamp'))){

            if($unit_stamp_files->isValid()){

                $img_path = $unit_stamp_files->store('yz/imgs/'.date('Y').'-'.date('m').'-'.date('d'));


                $imgRes  = self::addOssUploadImg($this->getMainUserId(),$this->ossClient, $unit_stamp_files, $img_path);
                if($imgRes['code'] === 0){
                    $data['unit_stamp'] = $imgRes['data'];
                }else{
                    return response()->json($imgRes);
                }
            }else{
                return response()->json(['code' => 1,'msg' => '单位印章，有错误！','data' => '']);
            }
        }
        //开启事务
        DB::beginTransaction();
        try{
            //医疗器械专用发货单
            $updData = $data;
            if(isset($data['deliver_time'])) $updData['deliver_time'] = strtotime($data['deliver_time']);

            $condition['user_id'] = $this->getUserId();
            $condition['main_id'] = $this->getMainUserId();
            $condition['id']      = $updData['medical_deliver_id'];

         /*    $updData['goods_info']='[
            {"goods_id":1,"name":"葡萄888","type_name":"紫8888","product_unit":"红富士888","price":"5.611","num":"1011","serial_number":11,"manufacturer":"掌上网络1","batch_number":"ZS45647547567","date_in_produced":"2022-07-30 21:30:30","effective_date":"2023-07-30 21:30:30","storage_condition":"温度在15度以下","registration_number":"zc3252543253656546"},
            {"goods_id":2,"name":"水梨8888","type_name":"黄888","product_unit":"砀山梨8888","price":"3.6","num":"8","serial_number":22,"manufacturer":"掌上网络1","batch_number":"ZS45647547567","date_in_produced":"2022-07-30 21:30:30","effective_date":"2023-07-30 21:30:30","storage_condition":"温度在15度以下","registration_number":"zc3252543253656546"},
            {"name":"水梨8888","type_name":"黄888","product_unit":"砀山梨888","price":"3.6","num":"8","serial_number":22,"manufacturer":"掌上网络1","batch_number":"ZS45647547567","date_in_produced":"2022-07-30 21:30:30","effective_date":"2023-07-30 21:30:30","storage_condition":"温度在15度以下","registration_number":"zc3252543253656546"}
            ]'; */

            if(isset($updData['goods_info']) && !empty($updData['goods_info'])){

                $goodsInfo = json_decode($updData['goods_info'],true);

                if(is_array($goodsInfo)){
                    foreach ($goodsInfo as $value){//更新商品信息
                        //更新
                        if(isset($value['goods_id'])){

                            $dCondition['id'] = $value['goods_id'];

                            unset($value['goods_id']);

                            MedicalDeliverProductsModel::where($dCondition)->update($value);
                        }else{//添加

                            $value['created_at'] = time();
                            $value['user_id']    = $this->getUserId();
                            $value['main_id']    = $this->getMainUserId();
                            $value['medical_deliver_id']= $updData['medical_deliver_id'];


                            MedicalDeliverProductsModel::insert($value);
                        }
                    }
                }
                unset($updData['goods_info']);
            }
            unset($updData['medical_deliver_id']);
            $updData['updated_at']   = time();
            $bool = MedicalDeliverOrderService::update($condition,$updData);

            if($bool){
                if(!empty($unit_stamp_files = $request->file('unit_stamp'))){
                    //删除oss里的文件
                    $delOssRes = self::delOssFilePath($info['unit_stamp'], $this->ossClient, $this->getMainUserId());
                    if(!empty($delOssRes)){

                        return $this->fail('',$delOssRes);
                    };
                }
            }
            DB::commit();//提交事务
            $this->log("修改医疗器械专用发货单", $updData);
            return $this->success();
        }catch (\Exception $e){
            DB::rollBack();//事务回滚
            //异常响应
            return $this->fail($e->getMessage(),'修改医疗器械专用发货单');
        }

    }

    /**
     * 医疗器械专用发货单信息
     * @param medical_deliver_id
     */
    public function find(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'medical_deliver_id'       =>'required|integer',//医疗器械专用发货单id
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg'  => $info,
                'data' => '',
            ]);
        }

        $condition['id']      = $data['medical_deliver_id'];
     
        $info = MedicalDeliverOrderService::getMedicalDeliverOrderInfo($condition);
        $list = $info;
        if(!empty($info)){

            $list['goods_list']= MedicalDeliverProductsModel::where(['medical_deliver_id'=>$info['id']])->get();
        }
        $this->log("医疗器械专用发货单信息", $list);
       return $this->success($list);
    }

    /**
     * 医疗器械专用发货单列表
     */
    public function MedicalDeliverOrderList(Request $request){

        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'page_size' =>'required|integer',//页面大小
            'current_page' =>'required|integer',//当前页
        ], [
            'page_size.required' => '参数`页面大小`丢失',
            'page_size.integer' => '参数`页面大小`仅能为数字',
            'current_page.required' => '参数`当前页码`丢失',
            'current_page.integer' => '参数`当前页码`仅能为数字',
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        $id_arr01 = [];
        $id_arr02 = [];
        $medical_deliver_id_arr = [];

        $keyword = empty($data['keyword'])?'':$data['keyword'];
    if($this->getMainUserId() != 0){
        if($this->getUserId() == $this->getMainUserId()) {
                $condition['main_id'] = $this->getMainUserId();
            }
            else {
                if($this->isShareBillhead()) {

                    $condition['main_id'] = $this->getMainUserId();
                }else {
                    $condition['main_id'] = $this->getMainUserId();
                    $condition['user_id'] = $this->getUserId();
                }
            }
        }else{
            $condition['user_id'] = $this->getUserId();
        }
        if(!empty($keyword)){

            $goodsList = MedicalDeliverProductsModel::select('medical_deliver_id')
            ->where($condition)
            ->where(function($query) use ($keyword) {
                $query->orWhere('name', 'like', '%'.$keyword.'%');
                $query->orWhere('type_name', 'like', '%'.$keyword.'%');
                $query->orWhere('serial_number', 'like', '%'.$keyword.'%');
            })
            ->orderBy('medical_deliver_id','DESC')
            ->get()->toArray();

            if(!empty($goodsList)){

                foreach ($goodsList as $k=>$v){

                $id_arr01[$k] = $v['medical_deliver_id'];

                }
            }

            $list = MedicalDeliverOrderModel::select('id')->where($condition)
                ->where(function($query) use ($keyword) {
                    $query->orWhere('customer_name', 'like', '%'.$keyword.'%');
                    $query->orWhere('customer_address', 'like', '%'.$keyword.'%');
                })->orderBy('id','desc')
                ->get()->toArray();

                if(!empty($list)){

                    foreach ($list as $k=>$v){

                        $id_arr02[$k] = $v['id'];
                    }
                }

                $medical_deliver_id_arr = array_unique(array_merge($id_arr01,$id_arr02));

                if(empty($medical_deliver_id_arr)){

                    $medical_deliver_id_arr[0] ="0";
                }
        }

        $list = MedicalDeliverOrderService::getList($condition,$medical_deliver_id_arr,$data['page_size'],$data['current_page']);

        if(!empty($list['data'])){

            foreach ($list['data'] as &$value){

                $query = MedicalDeliverProductsModel::where('medical_deliver_id',$value['id']);

                if(!empty($id_arr01)){

                    $query->where(function($query) use ($keyword) {
                    $query->orWhere('name', 'like', '%'.$keyword.'%');
                    $query->orWhere('type_name', 'like', '%'.$keyword.'%');
                    $query->orWhere('serial_number', 'like', '%'.$keyword.'%');
                    });
                }
               $value['goods_info'] =  $query->get();
            }
        }
        $this->log("医疗器械专用发货单列表", $list);
        return $this->success($list);
    }


    /**
     * 图片上传到oss系统
     * @param unknown $client
     * @param unknown $file
     */
    static public function addOssUploadImg($mainId,$client,$file,$path){
        $res = handleUploadFileType($file);
        if(!empty($res)) return $res;
        $size = $file -> getSize();
         $result = saveFileSize(['main_id'=>$mainId], $size,$path);
        if($result['code'] == 1) return $result;
        try {

            $fullPath = '/uploads/'.$path;
            $ossPath  = ltrim($fullPath,'./');
            $path     = public_path().$fullPath;
            $client -> uploadFile(config('app.aliyun_oss_bucket'), $ossPath, $path);
            @unlink($path);
            $url = config('app.aliyun_oss_bucket_url').$fullPath;
            return ["code"=>0,"msg"=>"success","data"=>$url];

        } catch (\Exception $e) {

            return ["code"=>1,"msg"=>"OSS系统，上传图片失败！","data"=>""];
        }
    }

    /**
     * 删除oss里的文件
     * @param unknown $file
     * @param unknown $mainId
     */
    static public function delOssFilePath($file,$client,$mainId){
        if(empty($file)) return $file;
            DB::beginTransaction();
            try {
                $delPath = strstr($file, 'uploads/');
                $imgInfo=$client->getObjectMeta(config('app.aliyun_oss_bucket'), $delPath);
                AdminAddendumModel::where(['main_id'=>$mainId])
                ->decrement('file_total_size', $imgInfo['content-length']);
                $client -> deleteObject(config('app.aliyun_oss_bucket'), $delPath);
                DB::commit();
            } catch (\Exception $e) {
                DB::rollBack();
                return "";
            }
    }
}
